package com.cj.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadUtils {
//    name是上传表单的 name
    public static String upload(String name, HttpServletRequest req){
        Part part = null;
        try {
            part = req.getPart(name);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

//        获取文件上传时的名字
        String fileName = part.getSubmittedFileName();
//        使用UUID将名字变的不同
        fileName = UUID.randomUUID()+fileName;

//        创建存储图片的文件夹
        File file = new File("C:\\Users\\Administrator\\Desktop\\img");

        if (!file.exists()){
            file.mkdirs();
        }

//        拼接出写入图片的地址   必须要加 ”/“ ，否则文件夹和文件连接在一起
        String path = file +"/" + fileName;

        try {
            part.write(path);
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
